﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BToolkit
{
    public class NamedPipeClient
    {
        private NamedPipeClientStream pipeClient;
        private Thread readThread;
        public event Action<string> onReceivedMsg;

        public NamedPipeClient(string pipeName)
        {
            pipeClient = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
            readThread = new Thread(ReadMessages);
        }

        public bool Connect(int timeout = 5000)
        {
            try
            {
                pipeClient.Connect(timeout);
                readThread.Start();
                return true;
            }
            catch (TimeoutException)
            {
                return false;
            }
        }

        private void ReadMessages()
        {
            var reader = new StreamReader(pipeClient, Encoding.UTF8);
            while (pipeClient.IsConnected)
            {
                try
                {
                    string message = reader.ReadLine();
                    if (message != null)
                    {
                        onReceivedMsg?.Invoke(message);
                    }
                }
                catch
                {
                    Disconnect();
                }
            }
        }

        public void SendMsg(string message)
        {
            if (!pipeClient.IsConnected) return;

            var writer = new StreamWriter(pipeClient, Encoding.UTF8);
            writer.WriteLine(message);
            writer.Flush();
        }

        public void Disconnect()
        {
            if (pipeClient.IsConnected)
            {
                pipeClient.Close();
            }
        }
    }
}
